#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>

int data[4] = {0};
pthread_mutex_t mutex;
pthread_cond_t cond;
int r_index = 0, w_index = 0, count = 0;
void *thread1(void *arg)
{
  // 线程1 循环写入数据
  while (1)
  {
    // 加锁
    pthread_mutex_lock(&mutex);
    if (count == 4)
    {
      // 等待线程2发送信号(条件变量)
      printf("thread1 wait\n");
      pthread_cond_wait(&cond, &mutex);
    }

    // 赋值
    data[w_index++] = rand() % 100;
    printf("write data[%d] = %d\n", w_index, data[w_index - 1]);
    count++;
    w_index %= 4;

    // sleep(1);

    // 解锁
    pthread_mutex_unlock(&mutex);

    // 向线程2发送信号(条件变量)
    pthread_cond_signal(&cond);
    sleep(rand() % 3);
  }
}
void *thread2(void *arg)
{
  while (1)
  {
    // 加锁
    pthread_mutex_lock(&mutex);
    if (count == 0)
    {
      // 等待线程1发送信号(条件变量)
      printf("thread2 wait\n");
      pthread_cond_wait(&cond, &mutex);
    }

    // 读取数据
    printf("read data[%d] = %d\n", r_index, data[r_index++]);
    count--;
    r_index %= 4;
    // sleep(1);

    // 解锁
    pthread_mutex_unlock(&mutex);

    // 向线程1发送信号(条件变量)
    pthread_cond_signal(&cond);
    sleep(rand() % 3);
  }
}
int main()
{
  pthread_t tid1, tid2;
  int ret;
  // 初始化互斥锁
  pthread_mutex_init(&mutex, NULL);

  // 初始化条件变量
  pthread_cond_init(&cond, NULL);

  // 创建线程
  ret = pthread_create(&tid1, NULL, thread1, NULL);
  if (ret != 0)
  {
    printf("pthread_create error: %s\n", strerror(ret));
    exit(1);
  }
  ret = pthread_create(&tid2, NULL, thread2, NULL);
  if (ret != 0)
  {
    printf("pthread_create error: %s\n", strerror(ret));
    exit(1);
  }

  // 等待线程结束
  ret = pthread_join(tid1, NULL);
  if (ret != 0)
  {
    printf("pthread_join error: %s\n", strerror(ret));
    exit(1);
  }
  ret = pthread_join(tid2, NULL);
  if (ret != 0)
  {
    printf("pthread_join error: %s\n", strerror(ret));
    exit(1);
  }

  // 销毁互斥锁和条件变量
  pthread_mutex_destroy(&mutex);
  pthread_cond_destroy(&cond);

  return 0;
}